﻿using CleanArchitecture.Core.Helper;
using CleanArchitecture.Infrastructure.Entities;
using CleanArchitecture.Infrastructure.Interfaces.Business;
using CleanArchitecture.Infrastructure.Services.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using System.Linq;
using System.Threading.Tasks;

namespace CleanArchitecture.Web.MvcRouteConfig
{
    /// <summary>
    /// Represents Front route transformer
    /// 配合Column UrlRoute及Layout实现控制器路由跳转
    /// </summary>
    public class FrontRouteTransformer : DynamicRouteValueTransformer
    {
        private readonly IColumnService _columnService;

        public FrontRouteTransformer(IColumnService columnService)
        {
            _columnService = columnService;
        }

        public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
        {
            if (values == null)
                return new ValueTask<RouteValueDictionary>(values);

            if (!values.TryGetValue("language", out var language) || string.IsNullOrEmpty(language as string))
                return new ValueTask<RouteValueDictionary>(values);
            if (!values.TryGetValue("columntype", out var columntype) || string.IsNullOrEmpty(columntype as string))
                return new ValueTask<RouteValueDictionary>(values);
            if (!values.TryGetValue("SeName", out var slugValue) || string.IsNullOrEmpty(slugValue as string))
                return new ValueTask<RouteValueDictionary>(values);

            string routeUri = "/" + language as string + "/" + columntype as string + "/" + slugValue as string;

            var urlRecords = _columnService.GetColumnList();
            var columnRecord = urlRecords.FirstOrDefault(u => u.UrlRoute.Equals(routeUri.ToLower()));
            //no URL record found
            if (columnRecord == null)
                return new ValueTask<RouteValueDictionary>(values);
            //virtual directory path
            //var pathBase = httpContext.Request.PathBase;
            //if(columnRecord.IsDisplay == EntityEnumConfig.YesorNo.No)
            //{
            //    //redirect to PageNotFound
            //    values[DefaultFrontRoutePath.ControllerFieldKey] = "Common";
            //    values[DefaultFrontRoutePath.ActionFieldKey] = "PageNotFound";
            //    httpContext.Items["nowa.RedirectFromFrontPathRoute"] = true;

            //    return new ValueTask<RouteValueDictionary>(values);
            //}

            //if URL record is not active let's find the latest one
            //if (columnRecord.IsActive == EntityEnumConfig.YesorNo.YES)
            //{
            switch (columnRecord.ColumnType)
            {
                case EntityEnumConfig.ColumnType.NewsColumn:
                    //redirect to active slug if found
                    values[DefaultFrontRoutePath.ControllerFieldKey] = "Article";
                    if (columnRecord.LayoutType == EntityEnumConfig.PageLayoutType.ArticleList)
                        values[DefaultFrontRoutePath.ActionFieldKey] = "List";
                    else if (columnRecord.LayoutType == EntityEnumConfig.PageLayoutType.SingleDetailPage)
                        values[DefaultFrontRoutePath.ActionFieldKey] = "Detail";
                    else
                        values[DefaultFrontRoutePath.ActionFieldKey] = "Unknown";

                    values[DefaultFrontRoutePath.ColumnFieldKey] = columnRecord.Id.IdEncode();//HashidsHelper.Encode(AuthenticationDefaultConfig.ItemIdHashSalt, columnRecord.Id);
                    values[DefaultFrontRoutePath.PermanentRedirectFieldKey] = true;
                    httpContext.Items["nowa.RedirectFromFrontPathRoute"] = true;
                    break;
                case EntityEnumConfig.ColumnType.BlogColumn:
                    //redirect to active slug if found
                    values[DefaultFrontRoutePath.ControllerFieldKey] = "Blog";
                    if (columnRecord.LayoutType == EntityEnumConfig.PageLayoutType.ArticleList)
                        values[DefaultFrontRoutePath.ActionFieldKey] = "List";
                    else if (columnRecord.LayoutType == EntityEnumConfig.PageLayoutType.SingleDetailPage)
                        values[DefaultFrontRoutePath.ActionFieldKey] = "Detail";
                    else
                        values[DefaultFrontRoutePath.ActionFieldKey] = "Unknown";

                    values[DefaultFrontRoutePath.ColumnFieldKey] = HashidsHelper.Encode(AuthenticationDefaultConfig.ItemIdHashSalt, columnRecord.Id);
                    values[DefaultFrontRoutePath.PermanentRedirectFieldKey] = true;
                    httpContext.Items["nowa.RedirectFromFrontPathRoute"] = true;
                    break;
                default:
                    values[DefaultFrontRoutePath.ControllerFieldKey] = "Home";
                    values[DefaultFrontRoutePath.ActionFieldKey] = "Index";
                    values[DefaultFrontRoutePath.PermanentRedirectFieldKey] = true;
                    httpContext.Items["nowa.RedirectFromFrontPathRoute"] = true;
                    break;
            }

            return new ValueTask<RouteValueDictionary>(values);
            //}
            //return new ValueTask<RouteValueDictionary>(values);
        }
    }
}
